package org.phalanx.digest;

import java.security.MessageDigest;
import java.util.StringTokenizer;

public class MessageDigestManager {
	private static String parseMD5Code(String buffer){
		String code = null;
		boolean resultFound = false;
		StringTokenizer tokenInput = new StringTokenizer(buffer);
		
		while (!resultFound && tokenInput.hasMoreTokens()){
			String currentToken = tokenInput.nextToken();
			//System.out.println(currentToken);
			
			if (currentToken.equalsIgnoreCase("Der")){
				String[] noHash = new String[2];
				for (int i = 0; tokenInput.hasMoreTokens() && i < 2; i++){
					noHash[i] = tokenInput.nextToken();
				}
				
				if (noHash[0].equalsIgnoreCase("Hash") && noHash[1].equalsIgnoreCase("konnte")){
					code = null;
				}
			}
			
			if (currentToken.equalsIgnoreCase("Code:")){
				String hashKey = tokenInput.nextToken();
				code = hashKey.substring(3, hashKey.length() - 8);
			}
			
		}
		
		return code;
	}
	
	public static String getMD5Hash(String key){
		String md5Hash = new String();
		try {
			byte[] keyBytes = key.getBytes();
			byte[] hashBytes = new byte[17];
			MessageDigest md5Encrypt = MessageDigest.getInstance("MD5");
			
			md5Encrypt.update(keyBytes);
			hashBytes = md5Encrypt.digest();
			md5Hash = convertHashToString(hashBytes, 16);
			
			return md5Hash;
		} catch (Exception e){
			return md5Hash;
		}
	}
	
	public static String getMD5Hash(byte[] key){
		String md5Hash = new String();
		try {
			byte[] keyBytes = key;
			byte[] hashBytes = new byte[17];
			MessageDigest md5Encrypt = MessageDigest.getInstance("MD5");
			
			md5Encrypt.update(keyBytes);
			hashBytes = md5Encrypt.digest();
			md5Hash = convertHashToString(hashBytes, 16);
			
			return md5Hash;
		} catch (Exception e){
			return md5Hash;
		}
	}
	
	public static byte[] getMD5HashBytes(String key){
		String md5Hash = new String();
		byte[] hashBytes = new byte[17];

		try {
			byte[] keyBytes = key.getBytes();
			MessageDigest md5Encrypt = MessageDigest.getInstance("MD5");
			
			md5Encrypt.update(keyBytes);
			hashBytes = md5Encrypt.digest();
			
		} catch (Exception e){
		}
		return hashBytes;
	}
	
	private static String convertHashToString(byte[] b, int hashLength){
		StringBuffer appendString = new StringBuffer();
		String hashString = new String();
		
		for (int i = 0; i <= hashLength - 1; i++){
			/*if (b[i] < 0){
			 p = ((b[i]>>>4)&0x0F);
			 }
			 else {
			 p = b[i];
			 }*/
			appendString.append(Integer.toHexString((b[i] & 0xFF) | 0x100).substring(1,3));
		}
		
		hashString = appendString.toString();
		
		return hashString;
	}
	

}
